package a_doubleWrite;

/**
 * 构建前缀树,时间复杂度：插入：O(n)，查找：O(n)，空间复杂度：O(26^n)
 *
 * @author: luolidong
 * @create: 2021-07-21 22:14
 * @version: 1.0
 */
public class TireTree {
    //每个节点的下一个可以是a-z 26个
    private class TireNode {
        boolean isEnd;
        TireNode[] next;

        //初始化false和next数组
        public TireNode() {
            this.isEnd = false;
            this.next = new TireNode[26];
        }
    }

    private TireNode root;

    //初始化根节点
    public TireTree() {
        root = new TireNode();
    }

    public void insert(String word) {
        TireNode curNode = root;//迭代，不能直接使用root
        for (char c : word.toCharArray()) {
            if (curNode.next[c - 'a'] == null) {
                curNode.next[c - 'a'] = new TireNode();
            }
            curNode = curNode.next[c - 'a'];
        }
        //结尾元素置为true
        curNode.isEnd = true;
    }

    public boolean search(String word) {
        TireNode curNode = root;//迭代，不能直接使用root
        for (char c : word.toCharArray()) {
            if (curNode.next[c - 'a'] == null) {
                return false;
            }
            curNode = curNode.next[c - 'a'];
        }
        //全部遍历完了,还要判断是否结尾
        return curNode.isEnd;
    }

    public boolean startsWith(String prefix) {
        TireNode curNode = root;//迭代，不能直接使用root
        for (char c : prefix.toCharArray()) {
            if (curNode.next[c - 'a'] == null) {
                return false;
            }
            curNode = curNode.next[c - 'a'];
        }
        //全部遍历完了
        return true;
    }

    public static void main(String[] args) {
        TireTree tireTree = new TireTree();
        tireTree.insert("apple");
        tireTree.insert("app");
        tireTree.insert("application");
        tireTree.insert("append");

        System.out.println("tireTree.search(\"appl\") = " + tireTree.search("apple"));
        System.out.println("tireTree.startsWith(\"appli\") = " + tireTree.startsWith("ppli"));
    }
}
